<?php
// 启动Composer自动加载
require_once 'vendor/autoload.php';

use App\Router;
use App\Controllers\UserController;
use App\Controllers\ChatController;

// ==================== 添加 CORS 支持 ====================
header("Access-Control-Allow-Origin: http://127.0.0.1:8080"); // 允许前端来源
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); // 允许的方法
header("Access-Control-Allow-Headers: Content-Type, Authorization"); // 允许的请求头
header("Access-Control-Max-Age: 3600"); // 预检缓存时间（秒）

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}
// =========================================================

// 创建路由实例
$router = new Router();

// 创建控制器实例
$userController = new UserController();
$chatController = new ChatController();

// 定义路由
// 用户的路由
$router->add('POST', '/user/register', [$userController, 'register']);
$router->add('POST', '/user/login', [$userController, 'login']);
$router->add('GET', '/user/profile', [$userController, 'profile']); // 需要授权的接口
$router->add('POST', '/user/logout', [$userController, 'logout']);  // 退出登陆注销token，防止还有人在使用这个token登陆
$router->add('POST', '/user/refresh-token', [$userController, 'refreshToken']);
$router->add('POST', '/user/check-userId', [$userController, 'validateUserId']);

// 消息处理的路由
$router->add('GET', '/user/contacts', [$chatController, 'getContacts']);
$router->add('GET', '/group/list', [$chatController, 'getGroups']);
$router->add('POST', '/message/send', [$chatController, 'sendMessage']);
$router->add('GET', '/message/history', [$chatController, 'getHistory']);
$router->add('POST', '/message/read', [$chatController, 'markAsRead']);
$router->add('GET', '/message/unread', [$chatController, 'getUnreadCount']);
$router->add('POST', '/message/revoke', [$chatController, 'revokeMessage']);
$router->add('GET', '/user/conversations', [$chatController, 'getConversations']);
$router->add('GET', '/chat/search', [$chatController, 'searchMessages']);

// 运行路由
$router->run();
exit;
?>